package com.lengtouzai.databaseexp.view.main;

import com.lengtouzai.databaseexp.entity.Journal;
import com.lengtouzai.databaseexp.entity.User;
import com.lengtouzai.databaseexp.view.journalcomponent.JournalComponent;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.router.Route;
import io.jmix.core.security.CurrentAuthentication;
import io.jmix.flowui.UiComponents;
import io.jmix.flowui.app.main.StandardMainView;
import io.jmix.flowui.model.CollectionContainer;
import io.jmix.flowui.model.CollectionLoader;
import io.jmix.flowui.view.Subscribe;
import io.jmix.flowui.view.ViewComponent;
import io.jmix.flowui.view.ViewController;
import io.jmix.flowui.view.ViewDescriptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Route("")
@ViewController("exp_MainView")
@ViewDescriptor("main-view.xml")
public class MainView extends StandardMainView {
    private static final Logger log = LoggerFactory.getLogger(MainView.class);
    @ViewComponent
    private CollectionLoader<Journal> journalsDl;
    @Autowired
    private CurrentAuthentication currentAuthentication;
    @ViewComponent
    private CollectionContainer<Journal> journalsDc;
    @ViewComponent
    private Div journalList;
    @Autowired
    private UiComponents uiComponents;

    @Subscribe
    public void onReady(final ReadyEvent event) {
        User current = (User) currentAuthentication.getUser();
        if (!current.getUsername().equals("admin")) {
            journalsDl.setParameter("user", current);
        }
        journalsDl.load();

        List<Journal> journals = journalsDc.getItems();
        for (Journal journal : journals) {
            JournalComponent journalComponent = uiComponents.create(JournalComponent.class);
            journalComponent.setJournal(journal);
            journalList.add(journalComponent);
        }
    }
}
